package cn.enilu.guns.admin.modular.door;

import cn.enilu.guns.admin.core.base.controller.BaseController;
import cn.enilu.guns.admin.core.base.tips.SetDataToDeviceTip;
import cn.enilu.guns.admin.equipment.service.EntranceGuardService;
import cn.enilu.guns.admin.equipment.transform.GetDeviceDataTransform;
import cn.enilu.guns.bean.core.ShiroUser;
import cn.enilu.guns.bean.dto.RealTimeRecordDto;
import cn.enilu.guns.bean.entity.door.EquipmentInfo;
import cn.enilu.guns.bean.entity.door.EventType;
import cn.enilu.guns.bean.vo.query.SearchFilter;
import cn.enilu.guns.service.door.EquipmentInfoService;
import cn.enilu.guns.service.door.EventTypeService;
import cn.enilu.guns.service.system.impl.ConstantFactory;
import cn.enilu.guns.shiro.ShiroKit;
import cn.enilu.guns.utils.BeanUtil;
import cn.enilu.guns.utils.Lists;
import cn.enilu.guns.utils.Maps;
import cn.enilu.guns.utils.StringUtils;
import cn.enilu.guns.warpper.door.EquipmentInfoWarpper;
import cn.enilu.guns.warpper.door.RealTimeRecordDtoWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Controller
//@RequestMapping("/door/real/time")
public class RealTimeControllerBak extends BaseController {
	private  Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private EntranceGuardService entranceGuardService;
	@Autowired
	private EquipmentInfoService equipmentInfoService;
    @Autowired
    private EventTypeService eventTypeService;

	public static final String REAL_TIME = "realTime";

	private static String PREFIX = "/door/real/time/";

	/**
	* 跳转到首页
	*/
	@RequestMapping(value="",method = RequestMethod.GET)
		public String index() {
			//设置开启监控的设备列表，放入Session中
			Map<Long,EquipmentInfo> openEquipmentInfos = Maps.newHashMap();
			setOpenRealTimeMap(openEquipmentInfos);
			return PREFIX + "index.html";
		}

	/**
	 * 获取所有的设备数据
	 * @param equipmentName
	 * @return
	 */
	@RequestMapping(value = "/listEquipment",method = RequestMethod.POST)
	@ResponseBody
	public Object listEquipment(@RequestParam(required = false) String equipmentName) {
		Map<Long,EquipmentInfo> openEquipmentInfoMap = getOpenRealTimeMap();
		List<SearchFilter> searchFilters = Lists.newArrayList();
		if(!StringUtils.isNullOrEmpty(equipmentName)) {
			searchFilters.add(SearchFilter.build("equipmentName", SearchFilter.Operator.EQ, equipmentName));
		}
		List<EquipmentInfo> equipmentInfos = equipmentInfoService.queryAll(searchFilters, new Sort(Sort.Direction.ASC, "id"));
		for (EquipmentInfo equipmentInfo:equipmentInfos) {
			if(openEquipmentInfoMap.containsKey(equipmentInfo.getId())){
				equipmentInfo.setOpenStatus("1");
			}else{
				equipmentInfo.setOpenStatus("0");
			}
//			if(entranceGuardService.checkDeviceOnline(equipmentInfo.getIpAddress())){
//				equipmentInfo.setOnlineStatus("1");
//			}else{
//				equipmentInfo.setOnlineStatus("0");
//			}
		}
		return super.warpObject(new EquipmentInfoWarpper(BeanUtil.objectsToMaps(equipmentInfos)));
	}
	/**
	* 关闭监控
	*/
	@RequestMapping(value = "/closeRealTime")
	@ResponseBody
	public Object closeRealTime(EquipmentInfo equipmentInfo) {
		equipmentInfo = equipmentInfoService.get(equipmentInfo.getId());
		SetDataToDeviceTip setDataToDeviceTip;
		if(entranceGuardService.checkDeviceOnline(equipmentInfo.getIpAddress())){
			Map<Long,EquipmentInfo> openEquipmentInfoMap = getOpenRealTimeMap();
			if(openEquipmentInfoMap.containsKey(equipmentInfo.getId())) {
				openEquipmentInfoMap.remove(equipmentInfo.getId(),equipmentInfo);
			}
			setOpenRealTimeMap(openEquipmentInfoMap);
			setDataToDeviceTip = new SetDataToDeviceTip(200,"关闭监控成功");
		}else{
			setDataToDeviceTip = new SetDataToDeviceTip(200,"关闭监控失败,设备不在线");
		}

        return setDataToDeviceTip;
	}
	/**
	 * 开启监控
	 */
	@RequestMapping(value = "/openRealTime")
	@ResponseBody
	public Object openRealTime(EquipmentInfo equipmentInfo) {
		equipmentInfo = equipmentInfoService.get(equipmentInfo.getId());
		SetDataToDeviceTip setDataToDeviceTip;
		if(entranceGuardService.checkDeviceOnline(equipmentInfo.getIpAddress())){
			Map<Long,EquipmentInfo> openEquipmentInfoMap = getOpenRealTimeMap();
			if(!openEquipmentInfoMap.containsKey(equipmentInfo.getId())) {
				openEquipmentInfoMap.put(equipmentInfo.getId(),equipmentInfo);
			}
			setOpenRealTimeMap(openEquipmentInfoMap);
			setDataToDeviceTip = new SetDataToDeviceTip(200,"开启监控成功");
		}else{
			setDataToDeviceTip = new SetDataToDeviceTip(200,"开启监控失败,设备不在线");
		}
		return setDataToDeviceTip;
	}

	/**
	 * Session中获取开启监控的设备列表
	 * @return
	 */
	private Map<Long,EquipmentInfo> getOpenRealTimeMap(){
		HttpSession session = this.getSession();
		ShiroUser shiroUser = ShiroKit.getUser();
		return (Map<Long,EquipmentInfo>)session.getAttribute(REAL_TIME + shiroUser.getId());
	}

	/**
	 * 设置开启监控的设备列表，放入Session中
	 * @param equipmentInfos
	 * @return
	 */
	private void setOpenRealTimeMap(Map<Long,EquipmentInfo> equipmentInfos){
		HttpSession session = this.getSession();
		ShiroUser shiroUser = ShiroKit.getUser();
		session.setAttribute(REAL_TIME + shiroUser.getId(),equipmentInfos);
	}


	//获取实时数据，返回list
	@RequestMapping(value = "/listRealTimeRecord",method = RequestMethod.POST)
	@ResponseBody
	public Object listRealTimeRecord(@RequestParam(required = false) String equipmentName) {
		List<RealTimeRecordDto> realTimeRecordDtos = Lists.newArrayList();
		Map<Long, EquipmentInfo> openEquipmentInfoMap = getOpenRealTimeMap();
		Map<Integer, EquipmentInfo> hCommPros = new HashMap<>();
		for (Map.Entry<Long, EquipmentInfo> m : openEquipmentInfoMap.entrySet()){
			int hCommPro = entranceGuardService.getHCommPro(m.getValue().getIpAddress());
			if(hCommPro != 0){
				hCommPros.put(hCommPro,m.getValue());
			}
		}
		long t1 = System.currentTimeMillis();
		while(true) {
			if(openEquipmentInfoMap.size() == 0){
				break;
			}
			long t2 = System.currentTimeMillis();
			try {
				if (t2 - t1 > 120 * 1000) {
					break;
				}
				for (Map.Entry<Integer, EquipmentInfo> m : hCommPros.entrySet()) {
//					Thread.sleep(1000);
//					logger.error("-----------------调用获取实时数据方法----------------------");
					String rtLog = entranceGuardService.getRTLog(m.getKey());
//					String rtLog = entranceGuardService.getRTLog(m.getValue().getIpAddress());
					if ("0".equals(rtLog)) {
						continue;
					}
					EquipmentInfo equipmentInfo = m.getValue();
					RealTimeRecordDto realTimeRecordDto = GetDeviceDataTransform.transformToRealTimeRecord(rtLog);
					realTimeRecordDto.setEquipmentId(equipmentInfo.getId());
					realTimeRecordDto.setEquipmentName(equipmentInfo.getEquipmentName());
					realTimeRecordDto.setAreaName(ConstantFactory.me().getAreaName(equipmentInfo.getAreaId().intValue()));
					realTimeRecordDto.setVerifiedName(ConstantFactory.me().getVerifiedName(realTimeRecordDto.getVerified()));
					EventType eventType = eventTypeService.findByEventCode(realTimeRecordDto.getEventType());
					if (eventType != null) {
						realTimeRecordDto.setEventName(eventType.getEventName());
						realTimeRecordDto.setEventStatus(eventType.getEventStatus());
					}
					realTimeRecordDto.setDoorName(realTimeRecordDto.getEquipmentName() + "-" + realTimeRecordDto.getDoorId());
					realTimeRecordDto.setUserName(ConstantFactory.me().getUserAccountById(realTimeRecordDto.getPin()));
					realTimeRecordDto.setInoutState(ConstantFactory.me().getInoutStateName(Integer.valueOf(realTimeRecordDto.getInoutState())));
					realTimeRecordDtos.add(realTimeRecordDto);
				}
			}catch(Exception e){
				logger.error("获取实时数据失败:",e.getStackTrace());
				break;
			}
			if(realTimeRecordDtos.size() > 0){
				break;
			}
		}
        return super.warpObject(new RealTimeRecordDtoWarpper(BeanUtil.objectsToMaps(realTimeRecordDtos)));
	}
}